package com.study.行为型模式.观察者模式;


import java.util.ArrayList;

public class WeatherData implements Subject{

    //温度，气压，湿度
    private float temperature;
    private float pressure;
    private float humidity;
    private ArrayList<Observer> observers;

    public WeatherData(){
        observers = new ArrayList<>();
    }

    //含有观察者集合，使用ArrayList管理

    //注册一个观察者
    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    //移除一个观察者
    @Override
    public void removeObserver(Observer o) {
        if (observers.contains(o)){
            observers.remove(o);
        }
    }

    //遍历观察者集合，调用观察者的update方法
    @Override
    public void notifyObservers() {

        for (Observer observer : observers) {
            observer.update(temperature,pressure,humidity);
        }
    }

    //当数据又更新时，就调用setData
    public void setData(float temperature, float pressure, float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        notifyObservers();
    }
}
